package persistence;

import java.util.List;

import javax.persistence.EntityManager;

import model.Contact;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


/**
 * 
 * @author Justin Templemore
 * @author hbriand (modified version for this project)
 * 
 * @class ContactDAO
 * @desc Maps a Contact with its table in DB
 */
public class ContactDAO
{
	private EntityManager currentEM;
	
	protected static Log log = LogFactory.getLog(ContactDAO.class);
	
	public ContactDAO ()
	{
		this.currentEM = PersistenceUtil.getEM();
	}
	protected EntityManager getEM()
	{
		return currentEM;
	}
	public void persist (Contact contact)
	{
		currentEM.persist(contact);
	}
	public void remove (Contact contact)
	{
		currentEM.remove(contact);
	}
	public Contact merge (Contact contact)
	{
		return (Contact)currentEM.merge (contact);
	}
	public void refresh (Contact contact)
	{
		currentEM.refresh (contact);
	}
	@SuppressWarnings("unchecked")
	public List<Contact> findSome (int first, int max)
	{
		return (List<Contact>) currentEM.createQuery("from Contact as m").setFirstResult(first).setMaxResults(max).getResultList();
	}
	@SuppressWarnings("unchecked")
	public List<Contact> findAll ()
	{
		return (List<Contact>) currentEM.createQuery("from Contact as m order by m.name").getResultList();
	}
	public long count ()
	{
		return ((Long) currentEM.createQuery("select count(m) from Contact m").getSingleResult()).longValue();
	}

    public void close() {
        this.currentEM.close();
    }
	public Contact findById(long cid) {
		return (Contact)currentEM.createQuery("from Contact where id="+cid).getSingleResult();
	}
}